define(['jquery', 'ThumbsChange', 'template'], ($, thumb, template) => {
  class Product {
    constructor (data) {
      // 储存已选择的规格
      this.body = data

      this.selected = {
        colorId: 0,
        modelId: 0,
        bundlePackageId: 0,
        num: 1
      }
      this.title = {
        colorIndex: '',
        modelIndex: 0,
        bundlePackageIndex: '0',
        color: '',
        version: '',
        memory: '',
        price: '',
        bundlePackage: ''
      }

      this.showMoreProm()
      this.bindEvent()

        this.renderInit()
        this.renderProm()
        this.renderShopInfo()
        this.handleProm()


      this.getShopNum()

      // 渲染图片
      new thumb()
    }

    showMoreProm () {
      $('.product-prom')
        .on('mouseenter', () => {
          $('.prom-more').show()
          $('.prom-less').hide()
        })
        .on('mouseleave', () => {
          $('.prom-more').hide()
          $('.prom-less').show()
        })
    }

    bindEvent () {
      const _this = this
      $('#colors').on('click', 'li', function () {
        // 添加选中样式
        $(this).addClass('selected').siblings().removeClass('selected')
        _this.selected.colorId = parseInt($(this).data('colorid'))
        // 保存选中颜色的索引
        _this.title.colorIndex = $(this).data('index')
        _this.title.color = $(this).find('span').html()
        _this.renderModel()
        _this.renderShopInfo()

        // 改变图片导航栏
        let selectedData = _this.body.product[_this.title.colorIndex]

        _this.selected.imgSrc = selectedData.picSrc[0]

        $('.thumbs-nav img').each((index, item) => {
          $(item).attr('src', selectedData.picSrc[index])
        })
        $('.thumbs-nav a').removeClass('current').eq(0).addClass('current')
        $('.product-gallery-img img, .product-gallery-img-big img').attr('src', selectedData.picSrc[0])
      })

      // 版本事件绑定
      $('#model').on('click', 'li', function () {
        $(this).addClass('selected').siblings().removeClass('selected')
        _this.selected.modelId = parseInt($(this).data('modelid'))
        _this.title.modelIndex = $(this).data('index')
        _this.renderShopInfo()
      })

      // 套餐事件绑定
      $('#bundlePackage').on('click', 'li', function () {
        $(this).addClass('selected').siblings().removeClass('selected')
        _this.selected.bundlePackageId = parseInt($(this).data('packageid'))
        _this.title.bundlePackageIndex = $(this).data('index')
        _this.renderShopInfo()
      })

      // 关闭添加对话框
      $('.box-close').on('click', function () {
        $('.add-cart').hide()
      })

      // 加入购物车
      $('.product-btn0').on('click', () => {
        this.addToCart()
      })

      // 数量+
      $('#selectedPlus').on('click', () => {
        this.selected.num++
        $('#selectedMinus').removeClass('disabled')
        $('#selectedNum').val(this.selected.num)
      })

      // 数量减
      $('#selectedMinus').on('click', () => {
        if (this.selected.num <= 1) {
          $('#selectedMinus').addClass('disabled')
          return false
        }
        this.selected.num--
        $('#selectedNum').val(this.selected.num)
      })

      // 手动修改数量
      $('.selected-num input').on('change', function () {
        let num = $(this).val()
        if (num <= 1 || !num) {
          num = 1
          $('#selectedMinus').addClass('disabled')
        } else {
          $('#selectedMinus').removeClass('disabled')
        }
        _this.selected.num = parseInt(num)
      })
    }

    renderInit () {
      // 通过渲染颜色分类，初始化规格选着
      $('#colors').html(template('colorTemplate', this.body)).find('li').eq(0)[0].click()
    }

    renderModel () {
      // 获取选中颜色的机型数据
      const selectProduct = this.body.product.filter(value => {
        return value.colorId === this.selected.colorId
      })

      // 判断是否拥有选中版本
      let isModelExist = selectProduct[0].model.some(value => value.modelId === this.selected.modelId ? value.able : false)
      // 修改选中版本
      if (!isModelExist) {
        // 之前选中版本不存在对应，修改为初始
        this.selected.modelId = selectProduct[0].model[0].modelId
        this.title.modelIndex = 0
      }

      // 判断是否拥有选中套餐
      let isBundlePackageExist = selectProduct[0].bundlePackage.some(value => {
        return value.packageID === this.selected.bundlePackageId ? value.able : false
      })
      // 修改选中套餐
      if (!isBundlePackageExist) {
        this.selected.bundlePackageId = selectProduct[0].bundlePackage[0].packageID
        this.title.bundlePackageIndex = 0
      }

      const product = {
        ...selectProduct[0],
        selectedModel: this.selected.modelId,
        selectedBundlePackage: this.selected.bundlePackageId
      }

      // 渲染子类规格
      $('#model').html(template('modelTemplate', product))
      $('#bundlePackage').html(template('packageTemplate', product))
    }

    renderShopInfo () {

      let model = this.body.product[this.title.colorIndex].model[this.title.modelIndex]
      this.bundle = this.body.product[this.title.colorIndex].bundlePackage[this.title.bundlePackageIndex]

      let price = model.price + this.bundle.price

      this.title.bundlePackage = this.bundle.package_name
      this.title.price = price
      this.title.version = model.version
      this.title.memory = model.memory
      this.title.id = parseInt(`${ this.body.id }0${ this.selected.colorId }0${ this.selected.modelId }`)

      this.titleInfo = `${ this.body.name } ${ this.title.version } ${ this.body.characteristic } ${ this.title.memory } ${ this.title.color }`
      const selectInfo = `${ this.title.color } / ${ this.title.version } ${ this.title.memory } / ${ this.title.bundlePackage }`
      $('.shopTitle').html(this.titleInfo)
      $('h1').html(`${ this.titleInfo } ${ this.title.bundlePackage }`)
      $('.price').html(this.title.price.toFixed(2))
      $('.selectedInfo').html(selectInfo)
      $('.shopid').html(this.title.id)
    }

    renderProm () {
      $('#prom').html(template('promTemplate', this.body))
    }

    setTop () {
      const $box = $('.add-box')
      const top = $(window).height() / 2 - $box.height() / 2
      $box.css('top', top)
    }

    addToCart () {
      this.handleProm()
      // 构造数据结构
      this.shopInfo = {
        id: this.title.id,
        href: `/detail.html?id=${ this.body.id }`,
        name: this.titleInfo,
        version: `${ this.title.color } ${ this.title.version } ${ this.title.memory }`,
        bundlePackage: { id: this.selected.bundlePackageId, name: this.title.bundlePackage, price: this.bundle.price },
        originPrice: this.title.price,
        price: this.price,
        num: this.selected.num,
        feature: this.body.feature,
        gift: this.prom.gift,
        sale: this.prom.sale,
        service: [],
        selected: true,
        imgSrc: this.selected.imgSrc
      }

      let cart = localStorage.getItem('cart')

      if (cart) {
        let cartJSON = JSON.parse(cart)

        const isExist = cartJSON.some(item => {
          return item.id === this.shopInfo.id && item.bundlePackage.id === this.shopInfo.bundlePackage.id
        })

        if (isExist) {
          cartJSON = cartJSON.map(item => {
            if (item.id === this.shopInfo.id && item.bundlePackage.id === this.shopInfo.bundlePackage.id) {
              item.num += this.shopInfo.num
            }
            return item
          })
        } else {
          cartJSON.push(this.shopInfo)
        }
        localStorage.setItem('cart', JSON.stringify(cartJSON))

      } else {
        localStorage.setItem('cart', JSON.stringify([this.shopInfo]))
      }

      // 修改页面显示
      $('.add-box-body-content span').html(`${this.titleInfo} x${this.selected.num}`)
      $('.add-cart').show()
      this.getShopNum()
      this.setTop()
    }

    getShopNum () {
      let cart = localStorage.getItem('cart')
      if (cart) {
        cart = JSON.parse(cart)
        this.total = cart.reduce((prev, item) => {
          return prev + item.num
        }, 0)
      } else {
        this.total = 0
      }

      let num = this.total
      if (this.total > 99) num = '99+'

      $('.shopNum').html(num)
    }

    handleProm () {
      this.prom = {}
      this.price = this.title.price
      let prom = this.body.prom
      prom.forEach(item => {
        if (item.name === '赠品') {
          this.prom.gift = item.content
        }

        if (item.name === '下单立减') {
          this.prom.sale = item.price
          this.price = this.title.price - item.price
        }
      })
    }
  }

  return Product
})
